FROM ubuntu:22.04

ENV DEBIAN_FRONTEND=noninteractive

# 安装依赖
RUN echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu focal main universe" >> /etc/apt/sources.list && \
    apt-get update && apt-get install -y \
    binutils libc-dev libc++-dev libgcc-7-dev wget tar gzip unzip build-essential ca-certificates git && \
    rm -rf /var/lib/apt/lists/*

# 编译 OpenSSL
WORKDIR /tmp
RUN wget https://www.openssl.org/source/openssl-3.0.12.tar.gz && \
    tar -xzf openssl-3.0.12.tar.gz && \
    cd openssl-3.0.12 && ./config --prefix=/usr/local/openssl && make -j$(nproc) && make install && \
    cd .. && rm -rf openssl-3.0.12*
RUN echo "/usr/local/openssl/lib" >> /etc/ld.so.conf && ldconfig

ENV OPENSSL_DIR=/usr/local/openssl
ENV PATH="${OPENSSL_DIR}/bin:${PATH}"
ENV LD_LIBRARY_PATH="${OPENSSL_DIR}/lib:${LD_LIBRARY_PATH}"

# 下载并安装 Cangjie SDK
WORKDIR /workspace
RUN wget -O cangjie-sdk-linux-x64-1.0.0.tar.gz "https://cangjie-lang.cn/v1/files/auth/downLoad?nsId=142267&fileName=cangjie-sdk-linux-x64-1.0.0.tar.gz&objectKey=68637fc53bcda926055851db" && \
    echo "8894e63a181bc0534af24263b449c2d8d4d9dfb16ff1270b793499fe06ce6dcf  cangjie-sdk-linux-x64-1.0.0.tar.gz" | sha256sum -c && \
    tar -xzf cangjie-sdk-linux-x64-1.0.0.tar.gz && \
    rm cangjie-sdk-linux-x64-1.0.0.tar.gz

# 下载 stdx
RUN wget https://gitcode.com/Cangjie/cangjie-stdx-bin/releases/download/v1.0.1.1/cangjie-stdx-linux-x64-1.0.1.1.zip && \
    unzip cangjie-stdx-linux-x64-1.0.1.1.zip && rm cangjie-stdx-linux-x64-1.0.1.1.zip

# 设置环境变量（关键：包含 tools 目录）
ENV CJ_HOME=/workspace/cangjie
ENV PATH="${CJ_HOME}/bin:${CJ_HOME}/tools:${PATH}"
ENV LD_LIBRARY_PATH="${CJ_HOME}/lib:${LD_LIBRARY_PATH}"

# 核心修复：强制 bash 启动时加载环境
RUN echo "source ${CJ_HOME}/envsetup.sh" >> /root/.bashrc

# 创建入口点脚本（打印信息 + 执行 bash）
RUN echo '#!/bin/bash\n\
echo "=== Cangjie Environment Initialized ==="\n\
echo "Cangjie SDK location: ${CJ_HOME}"\n\
echo "stdx location: /workspace/linux_x86_64_llvm/dynamic/stdx"\n\
echo ""\n\
echo "Running: cjc -v"\ncjc -v\n\
echo ""\n\
echo "Running: cjpm --version"\ncjpm --version\n\
echo ""\n\
exec "$@"' > /entrypoint.sh && chmod +x /entrypoint.sh

WORKDIR /workspace/projects
ENTRYPOINT ["/entrypoint.sh"]
CMD ["bash"]